package com.qf.anli.interceptors;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/*
    try{
        preHandle

        处理器方法

        postHandle

    }catch(Exception e){

    }finally{
        afterCompletion
    }
 */

public class LoginInterceptor implements HandlerInterceptor {
    //请求到达处理器方法之前执行。返回false，拦截；返回true，放行
    @Override
    public boolean preHandle(HttpServletRequest req, HttpServletResponse resp, Object handler) throws Exception {
        //进行是否登录的判断
        HttpSession session = req.getSession();

        Object user = session.getAttribute("user");
        if(user == null){
            //没有登录，去到登录页面
            resp.sendRedirect("/login.html");

            return false;
        }

        return true;
    }

    //处理器方法正常执行完后，执行的。如果处理器方法出现异常，不会执行的
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    //不管处理器方法是否正常执行结束，最后执行这个方法
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
